package com.bussiness.system.exception;

import com.bussiness.system.constant.ExceptionConstant;
import com.bussiness.system.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: xlr
 * @Date: 2018/8/13 10:39
 * @Description: controller 全局异常捕获
 */
@ControllerAdvice
public class MyServiceException extends RuntimeException {

    Logger logger = LoggerFactory.getLogger(MyServiceException.class);

    private String message;

    private Exception e;

    MyServiceException(){

    }

    public MyServiceException(String message){
        this.message = message;
    }

    public MyServiceException(String message, Exception e){
        this.message = message;
        this.e = e;
    }
    /**
     * 文件上传异常拦截
     * @param e
     * @return
     */
    @ExceptionHandler(MultipartException.class)
    @ResponseBody
    public Result multipartExceptionHander(MultipartException e){
        e.printStackTrace();
        logger.warn("文件上传错误{}",e.getMessage());
        return new Result<>().fail(ExceptionConstant.UPLOADEXCEPTION.getErrorCode(), ExceptionConstant.UPLOADEXCEPTION.getErrorMsg());
    }

    /**
     * 数据校验
     *
     * @param e
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public Result<Map> bindException(MethodArgumentNotValidException e){
        Map<String,String> map = new HashMap<>();
        List<FieldError> list = e.getBindingResult().getFieldErrors();
        for (FieldError allError : list) {
            map.put(allError.getField(),allError.getDefaultMessage());
            logger.warn("字段: {},错误描述: {}",allError.getField(),allError.getDefaultMessage());
        }
        return new Result<Map>().error(map);
    }

}
